package com.intellif.mozping.threadpool.invokeall;

import com.intellif.mozping.tools.SleepTools;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author by mozping
 * @Classname InvokeAllTest
 * @Description TODO
 * @Date 2019/10/19 10:08
 */
public class InvokeAllTimedTest {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        List<Callable<String>> list = new ArrayList<>();
        for (int i = 1; i < 10; i++) {
            list.add(new MyTask(i+""));
        }
        List<Future<String>> futures = null;
        try {
            futures = executorService.invokeAll(list, 3, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            System.err.println("InterruptedException ...");
            e.printStackTrace();
        }

        for (Future f : futures) {
            try {
                System.out.println(f.get() + " -- " + System.currentTimeMillis());
            } catch (InterruptedException e) {
                System.err.println("InterruptedException ...");
                e.printStackTrace();
            } catch (ExecutionException e) {
                System.err.println("ExecutionException ...");
                e.printStackTrace();
            }catch (Exception ex){
                System.out.println(ex.getClass());
            }
        }
        executorService.shutdown();
    }

    static class MyTask implements Callable<String> {

        String id;
        public MyTask(String id) {
            this.id = id;
        }

        @Override
        public String call() throws Exception {
            long begin = System.currentTimeMillis();
            SleepTools.randomMs(5000);
            return id +" -- "+ (System.currentTimeMillis() - begin);
        }
    }
}